//
//  AlbumViewDataSource.m
//  OntheRoadV4
//
//  Created by ZhangYanhua on 15/3/10.
//  Copyright (c) 2015年 EricHuang. All rights reserved.
//

#import "AlbumViewDataSource.h"
#import "MyAlbumLocation.h"
#import "QWImageMangerConfig.h"

@interface AlbumViewDataSource() {
    BOOL showPhotos;
    
    NSInteger imagesPerRow;
    
    BOOL canAccessAlbum;
    BOOL canAccessCamera;
    
    BOOL hasVideoDevice;
}

@property (nonatomic, retain) NSMutableArray  *assetGroups;
@property (nonatomic, strong) MyAssetsGroup   *selectedGroup;

@property (nonatomic, retain) NSMutableArray  *libAssets;
@property (nonatomic, assign) AssetsEnumStatus curEnumStatus;
@property (nonatomic, assign) NSUInteger      imageCntLimitation;
@property (nonatomic, assign) NSUInteger      didSelectImage;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableArray *photoBrowserArr;

@property (nonatomic, strong) NSMutableArray *takenPicURLs;
@property (nonatomic, strong) ALAsset *takenPicAsset;

@property (nonatomic, strong) MyAlbumLocation *position;

@end

@implementation AlbumViewDataSource

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (_selectedGroup) {
        [MyAlbumLocation setMyAlbumLocation:[[MyAlbumLocation alloc]
                                     initWithGroupUrl:_selectedGroup.groupIdentifier
                                     contentOffset:self.albumVC.tableView.contentOffset.y]];
    }
}

- (id)initWithTableViewController:(AlbumViewController *)viewController
                      maxImageCnt:(NSInteger)maxCnt
                       shwoPhotos:(BOOL)photos
{
    self = [super init];
    if (self) {
        _albumVC = viewController;
        showPhotos = photos;
        _imageCntLimitation = maxCnt;
        
        imagesPerRow = 3;
        if ([UIScreen mainScreen].bounds.size.width > 374.0f) {
            imagesPerRow = 4;
        }
        
        canAccessAlbum = [ALAssetsGroupEnumerator hasPermissionToAccessPhotoAndAlert:NO];
        canAccessCamera = [ALAssetsGroupEnumerator hasPermissionToAccessCameraAndAlert:NO];
        
        hasVideoDevice = ([[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count] > 0);
        
        _assetGroups = [[ALAssetsGroupEnumerator sharedInstance] getNotEmptyGroupsForPhoto:showPhotos];
        _takenPicURLs = [NSMutableArray array];

        _position = [MyAlbumLocation getMyAlbumLocation];
        _selectedAssets = [[NSMutableArray alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(applicationDidBecomeActive:)
                                                     name:UIApplicationDidBecomeActiveNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(albumUpdated:)
                                                     name:NOTIFICATION_ENUM_GROUP_FINISHED
                                                   object:nil];
    }

    return self;
}

- (void)applicationDidBecomeActive:(NSNotification *)notify
{
    BOOL curPhotoPermission = [ALAssetsGroupEnumerator hasPermissionToAccessPhotoAndAlert:NO];
    
    if (curPhotoPermission != canAccessAlbum) {
        canAccessAlbum = curPhotoPermission;
        
        [self reloadTableViewAndData:NO];
    }
}

- (void)albumUpdated:(NSNotification *)notify
{
    self.assetGroups = [[ALAssetsGroupEnumerator sharedInstance] getNotEmptyGroupsForPhoto:showPhotos];
    [self.albumVC.albumTableView reloadData];
    
    AssetsList *list = [notify.userInfo objectForKey:@"updatedList"];
    MyAssetsGroup *deletedGroup = [notify.userInfo objectForKey:@"deletedGroup"];
    
    if (deletedGroup) {
        // 剔除这个相册里面选中的照片
        [ImageAsset deletedAssetsOfArray:self.selectedAssets inGroup:deletedGroup.groupIdentifier];
        [self.albumVC updateNavBarTitleView];
        
        if (!self.selectedGroup || [self.selectedGroup isEqual:deletedGroup]) {
            MyAssetsGroup *group = [self.assetGroups firstObject];
            
            self.selectedGroup = group;
            
            [self.albumVC.albumTableView reloadData];
            [self.albumVC hideAlbumTableView];
            [self.albumVC updateNavBarTitleView];
            
            [self reloadTableViewAndData:YES];
        }
    }
    
    if (list) {
        // 剔除被删除的照片
        if (list.enumStatus == ASSETS_ENUM_FINISHED) {
            NSArray *tempArray = [self.selectedAssets copy];
            for (ImageAsset *selAsset in tempArray) {
                if ([selAsset.groupIdentifier isEqualToString:list.myGroup.groupIdentifier]) {
                    if (![list.photos containsObject:selAsset]) {
                        [self.selectedAssets removeObject:selAsset];
                    }
                }
            }
        }
        
        // 自动选中程序内的拍照
        NSArray *tempArray = [self.takenPicURLs copy];
        for (int i = 0; i < tempArray.count; i++) {
            NSString *takenAssetURLStr = tempArray[i];
            
            NSArray *curListArray = [list.photos copy];
            for (int i = 0; i < 20 && i < curListArray.count ; i++) {
                ImageAsset *imgAsset = curListArray[i];
                
                //判断assetIdentifier 类型
                NSString *assetIdentifier = nil;
                if ([imgAsset.assetIdentifier isKindOfClass:[NSURL class]])
                {
                    assetIdentifier = [(NSURL*)imgAsset.assetIdentifier absoluteString];
                }else
                {
                    assetIdentifier = imgAsset.assetIdentifier;
                }
                if ([assetIdentifier isEqualToString:takenAssetURLStr]) {
                    [self.selectedAssets insertObject:imgAsset atIndex:0];
                    self.didSelectImage = [self.selectedAssets count];
                    [self.takenPicURLs removeObject:takenAssetURLStr];
                    
                    break;
                }
            }
        }
        
        [self.albumVC updateNavBarTitleView];
        
        // 更新当前的相册
        if ([self.selectedGroup isEqual:list.myGroup]) {
            [self reloadTableViewAndData:YES];
        }
    }
}

- (NSString *)selectedGroupName
{
    return self.selectedGroup.groupName;
}

- (NSUInteger)numberOfAssetsGroup
{
    return [self.assetGroups count];
}

- (NSUInteger)indexOfSelectedGroup
{
    if (!self.selectedGroup) {
        return NSNotFound;
    }

    return [self.assetGroups indexOfObject:self.selectedGroup];
}

- (void)loadLastAlbum
{
    _selectedGroup = [self.assetGroups firstObject];
    if (self.position) {
        for (int i = 0; i < [self.assetGroups count]; i++) {
            MyAssetsGroup *group = [self.assetGroups objectAtIndex:i];
            if ([self.position.groupUrl isEqualToString:group.groupIdentifier]) {
                _selectedGroup = group;
                break;
            }
        }
    }
    
    [self.albumVC updateNavBarTitleView];
    
    if (_selectedGroup) {
        [self reloadTableViewAndData:YES];
    }
}

#pragma mark -
#pragma mark Table view data source

- (void)prepareDataArray
{
    NSMutableArray *tempArray = [self.libAssets mutableCopy];
    
    NSMutableArray *result = [NSMutableArray array];
    NSMutableArray *sectionArray = [NSMutableArray array];
    if (showPhotos && hasVideoDevice) {
        [sectionArray addObject:[[ImageAsset alloc] init]];
    }
    
    ImageAsset *lastImgAsset = nil;
    for (int i = 0; i < tempArray.count; i++) {
        ImageAsset *curImgAsset = tempArray[i];
        
        if ([curImgAsset isInTheSameSectionWithAsset:lastImgAsset tenDaysAfterFirstDate:nil]) {
            [sectionArray addObject:curImgAsset];
        } else {
            if ([sectionArray count] > 0) {
                [result addObject:sectionArray];
            }
            
            sectionArray = [NSMutableArray array];
            [sectionArray addObject:curImgAsset];
        }
        
        lastImgAsset = curImgAsset;
    }
    
    if ([sectionArray count] > 0) {
        [result addObject:sectionArray];
    }
    
    self.dataArray = result;
}

- (void)reloadTableViewAndData:(BOOL)reloadData
{
    if (reloadData) {
        AssetsList *curList = [[ALAssetsGroupEnumerator sharedInstance] getAssetsListOfGroup:self.selectedGroup];
        self.libAssets = showPhotos ? [curList.photos mutableCopy] : [curList.videos mutableCopy];
        self.curEnumStatus = curList.enumStatus;
        
        [self prepareDataArray];
    }
    
    // 不能访问相册时，相机也不显示
    if (!canAccessAlbum) {
        [self.dataArray removeAllObjects];
    }
    
    [self.albumVC.tableView reloadData];
}

- (NSArray *)assetsForIndexPath:(NSIndexPath *)_indexPath
{
    NSArray *sectionArray = [self.dataArray objectAtIndex:_indexPath.section];
    
    NSInteger index = (_indexPath.row * imagesPerRow);
    NSInteger maxIndex = MIN((_indexPath.row * imagesPerRow + (imagesPerRow-1)), [sectionArray count] - 1);
    NSInteger length = MAX(0, maxIndex - index + 1);
    
    NSArray *result = [sectionArray subarrayWithRange:NSMakeRange(index, length)];
    
    return result;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        if (!canAccessAlbum) {
            self.albumVC.bgVideoIcon.hidden = YES;
            self.albumVC.bgVideoLabel.text = nil;
            
            self.albumVC.bgTitleLabel.text = QWImagePickerLocalizedString(@"This app does not have access to your photos!", nil);
            self.albumVC.bgSubTitleLabel.text = QWImagePickerLocalizedString(@"You can enable access in Privacy Settings.", nil);
            self.albumVC.tableView.backgroundView = self.albumVC.tableBgView;
        } else if (self.dataArray.count == 0) {
            self.albumVC.bgTitleLabel.text = nil;
            self.albumVC.bgSubTitleLabel.text = nil;
            
            if (showPhotos) {
                self.albumVC.bgVideoIcon.image = [QWImageMangerConfig  imageNamed:@"icon_camera_140_gary"];
                self.albumVC.bgVideoLabel.text = QWImagePickerLocalizedString(@"No captured photos", nil);
            } else {
                self.albumVC.bgVideoIcon.image = [QWImageMangerConfig  imageNamed:@"icon_video_140_gary"];
                self.albumVC.bgVideoLabel.text = QWImagePickerLocalizedString(@"No captured videos", nil);
            }
            self.albumVC.tableView.backgroundView = self.albumVC.tableBgView;
        } else {
            self.albumVC.tableView.backgroundView = nil;
        }
        
        if (self.curEnumStatus == ASSETS_ENUM_IN_PROGRESS) {
            [self.albumVC.loadingIndicator startAnimating];
        } else {
            [self.albumVC.loadingIndicator stopAnimating];
        }
        
        return [self.dataArray count];
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        NSArray *sectionArray = [self.dataArray objectAtIndex:section];
        
        return ([sectionArray count] + (imagesPerRow - 1)) / imagesPerRow;
    } else {
        return [self.assetGroups count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        NSArray *sectionArray = self.dataArray[indexPath.section];
        
        NSInteger numOfRows = ([sectionArray count] + (imagesPerRow - 1)) / imagesPerRow;
        
        BOOL isLastRow = indexPath.row + 1 == numOfRows;
        
        return [AlbumPhotoCell getCellHeightIsLastCell:isLastRow numberOfColumns:imagesPerRow];
    } else {
        return 60.0f;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        AlbumPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumPhotoCell"];
        if (cell == nil) {
            if ([UIScreen mainScreen].bounds.size.width > 374.0f) {
                cell = [[[QWImageMangerConfig baseBundle] loadNibNamed:@"AlbumPhotoCell_iPhone55" owner:self options:nil] lastObject];
            } else {
                cell = [[[QWImageMangerConfig baseBundle] loadNibNamed:@"AlbumPhotoCell" owner:self options:nil] lastObject];
            }
            cell.delegate = self;
        }
        
        NSArray *assets = [self assetsForIndexPath:indexPath];
        
        [cell updateCellContentWithArray:assets selectedArray:self.selectedAssets];
        
        if (indexPath.section == 0 && indexPath.row == 0 && showPhotos && hasVideoDevice) {
            AlbumPhotoCell *assetCell = (AlbumPhotoCell *)cell;
            
            UIView *view = [[assetCell imageViews] firstObject];
            CALayer *viewLayer = [view layer];
            [viewLayer setMasksToBounds:YES];
            
            CGRect bounds = [view bounds];
            [self.albumVC.previewLayer setFrame:bounds];
            
            [viewLayer addSublayer:self.albumVC.previewLayer];
        }
        
        return cell;
    } else {
        AlbumCoverCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumCoverCell"];
        if (cell == nil) {
            cell = [[[QWImageMangerConfig baseBundle] loadNibNamed:@"AlbumCoverCell" owner:self options:nil] lastObject];
        }
        
        MyAssetsGroup *group = [self.assetGroups objectAtIndex:indexPath.row];
        
        [cell updateCellWithGroup:group
                       showPhotos:showPhotos
                       isLastCell:(indexPath.row + 1 == self.assetGroups.count)];
        [cell updateSelectionState:([_selectedGroup isEqual:group])];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        if (indexPath.section == 0 && indexPath.row == 0 && showPhotos && hasVideoDevice) {
            AlbumPhotoCell *assetCell = (AlbumPhotoCell *)cell;
            
            UIView *view = [[assetCell imageViews] firstObject];
            CALayer *viewLayer = [view layer];
            [viewLayer setMasksToBounds:YES];
            
            CGRect bounds = [view bounds];
            [self.albumVC.previewLayer setFrame:bounds];
            
            [viewLayer addSublayer:self.albumVC.previewLayer];
        }
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        if (indexPath.row == 0 && indexPath.section == 0 && showPhotos && hasVideoDevice) {
            [self.albumVC.previewLayer removeFromSuperlayer];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        if (section == 0 && self.dataArray.count == 1 &&
            [(NSArray *)[self.dataArray firstObject] count] == 1) {
            return 6.0f;
        }
        return 46.0f;
    } else {
        return 5.0f;
    }
}

- (void)updateHeaderView:(AlbumSectionHeaderView *)headerView InSection:(NSInteger)section
{
    if (![headerView isKindOfClass:[AlbumSectionHeaderView class]]) {
        return;
    }
    
    NSArray *sectionArray = [self.dataArray objectAtIndex:section];
    ImageAsset *curImgAsset = [sectionArray lastObject];
    
    headerView.titleLabel.text = [QWImageMangerConfig convertDateToAlbumDateString:curImgAsset.assetDate];
    
    if (showPhotos) {
        BOOL isAllSelected = YES;
        for (int i = 0; i < sectionArray.count; i++) {
            ImageAsset *imgAsset = [sectionArray objectAtIndex:i];
            
            if (![self.selectedAssets containsObject:imgAsset] && imgAsset.asset) {
                isAllSelected = NO;
                break;
            }
        }
        
        if (isAllSelected) {
            [headerView updateSelectButtonWithTitle:QWImagePickerLocalizedString(@"Deselect", nil)];
        } else {
            [headerView updateSelectButtonWithTitle:QWImagePickerLocalizedString(@"Select", nil)];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        if (section == 0 && self.dataArray.count == 1 &&
            [(NSArray *)[self.dataArray firstObject] count] == 1) {
            return [[UIView alloc] initWithFrame:CGRectZero];
        }
        
        AlbumSectionHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"AlbumSectionHeaderView"];
        if (headerView == nil) {
            headerView = [[AlbumSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.frame.size.height)];
            [headerView setRestorationIdentifier:@"AlbumSectionHeaderView"];
            headerView.delegate = self;
            headerView.selectAllBtn.hidden = !showPhotos;
        }
        
        headerView.frame = CGRectMake(0.0f, 0.0f, self.albumVC.view.bounds.size.width, 46.0f);
        headerView.tag = section;
        
        [self updateHeaderView:headerView InSection:section];
        
        return headerView;
    }
    
    return [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.albumVC.view.bounds.size.width, 5.0f)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        return 0.0f;
    } else {
        return 5.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        return nil;
    }
    
    return [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.albumVC.view.bounds.size.width, 5.0f)];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.albumVC.tableView]) {
        return;
    } else {
        MyAssetsGroup *group = [self.assetGroups objectAtIndex:indexPath.row];
        if (![self.selectedGroup.groupIdentifier isEqualToString:group.groupIdentifier]) {
            self.selectedGroup = group;
            
            [self.albumVC.albumTableView reloadData];
            [self.albumVC hideAlbumTableView];
            [self.albumVC updateNavBarTitleView];
            [self reloadTableViewAndData:YES];
        }
    }
}

#pragma mark -
#pragma mark AlbumSectionHeaderViewDelegate

- (void)selectAllBtnPressedInView:(AlbumSectionHeaderView *)headerView
{
    NSInteger section = [headerView tag];
    
    if (section >= 0 && section < [self.dataArray count]) {
        NSArray *sectionArray = [self.dataArray objectAtIndex:section];
        
        BOOL isAllSelected = YES;
        for (int i = 0; i < sectionArray.count; i++) {
            ImageAsset *imgAsset = [sectionArray objectAtIndex:i];
            
            if (![self.selectedAssets containsObject:imgAsset] && imgAsset.asset) {
                isAllSelected = NO;
                break;
            }
        }
        
        if (isAllSelected) {
            for (int i = 0; i < sectionArray.count; i++) {
                ImageAsset *imgAsset = [sectionArray objectAtIndex:i];
                
                if ([self.selectedAssets containsObject:imgAsset] && imgAsset.asset) {
                    [self.selectedAssets removeObject:imgAsset];
                    
                    UITableViewCell *cell = [self.albumVC.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i / imagesPerRow
                                                                                                     inSection:section]];
                    [(AlbumPhotoCell *)cell updateCellSelectionState:NO AtIndex:i % imagesPerRow];
                }
            }
        } else {
            for (int i = 0; i < sectionArray.count; i++) {
                ImageAsset *imgAsset = [sectionArray objectAtIndex:i];
                
                if (![self.selectedAssets containsObject:imgAsset] && imgAsset.asset) {
                    if (self.selectedAssets.count >= self.imageCntLimitation) {
                        [QWImageMangerConfig alert:[NSString stringWithFormat:QWImagePickerLocalizedString(@"A maximum of %d images can be selected.", nil), self.imageCntLimitation]];
                        break;
                    }
                    
                    [self.selectedAssets addObject:imgAsset];
                    
                    UITableViewCell *cell = [self.albumVC.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i / imagesPerRow
                                                                                                     inSection:section]];
                    [(AlbumPhotoCell *)cell updateCellSelectionState:YES AtIndex:i % imagesPerRow];
                }
            }
        }
        
        [self updateHeaderView:headerView InSection:section];
        
        [self.albumVC updateNavBarTitleView];
    }
}

#pragma mark -
#pragma mark AlbumPhotoCellDelegate

- (void)albumPhotoCell:(AlbumPhotoCell *)cell didSelectAssetAtIndex:(NSInteger)index
{
    NSIndexPath *indexPath = [self.albumVC.tableView indexPathForCell:cell];
    
    if (!indexPath) {
        return;
    }
    
    NSArray *sectionArray = [self.dataArray objectAtIndex:indexPath.section];
    
    NSInteger dataIndex = indexPath.row * imagesPerRow + index;
    
    ImageAsset *imgAsset = [sectionArray objectAtIndex:dataIndex];
    if (![self.selectedAssets containsObject:imgAsset] && imgAsset.asset) {
        if (self.selectedAssets.count >= self.imageCntLimitation) {
            [QWImageMangerConfig alert:[NSString stringWithFormat:QWImagePickerLocalizedString(@"A maximum of %d images can be selected.", nil), self.imageCntLimitation]];
            return;
        }
        
        [self.selectedAssets addObject:imgAsset];
        
        [cell updateCellSelectionState:YES AtIndex:index];
    } else if (imgAsset.asset) {
        [self.selectedAssets removeObject:imgAsset];
        
        [cell updateCellSelectionState:NO AtIndex:index];
    }
    
    AlbumSectionHeaderView *headerView = (AlbumSectionHeaderView *)[self.albumVC.tableView headerViewForSection:indexPath.section];
    [self updateHeaderView:headerView InSection:indexPath.section];
    
    [self.albumVC updateNavBarTitleView];
}

- (void)albumPhotoCell:(AlbumPhotoCell *)cell didSelectImageAtIndex:(NSInteger)index
{
    NSIndexPath *indexPath = [self.albumVC.tableView indexPathForCell:cell];
    
    if (!indexPath) {
        return;
    }
    
    NSArray *sectionArray = [self.dataArray objectAtIndex:indexPath.section];
    
    NSInteger dataIndex = indexPath.row * imagesPerRow + index;
    
    ImageAsset *imgAsset = [sectionArray objectAtIndex:dataIndex];
    
    if (showPhotos) {
        index = [self.libAssets indexOfObject:imgAsset];
        
        if (index == NSNotFound || [self.libAssets count] == 0) {
            if (indexPath.row == 0 && indexPath.section == 0) {
                if (![ALAssetsGroupEnumerator hasPermissionToAccessCameraAndAlert:NO]) {
                    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"QWImagePickerNoPermissionAlertDate"];
                    
                    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:QWImagePickerLocalizedString(@"This app does not have access to your camera!", nil)
                                                                     message:QWImagePickerLocalizedString(@"You can enable access in Privacy Settings.", nil)
                                                                    delegate:nil
                                                           cancelButtonTitle:QWImagePickerLocalizedString(@"I know", nil)
                                                           otherButtonTitles:nil];
                    [alert show];
                } else if ([self.albumVC.delegate respondsToSelector:@selector(albumViewControllerShowCameraView)]) {
                    [self.albumVC.delegate albumViewControllerShowCameraView];
                }
            }
            
            return;
        }
        
        #warning 去掉MWPhotoBrowser 相关部分
        /*
        self.photoBrowserArr = [self.libAssets mutableCopy];
        
        MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        
        NSInteger startIndex = MIN(self.photoBrowserArr.count - 1, index);
        startIndex = MAX(0, startIndex);
        [browser setInitialPageIndex:startIndex]; // Show second page first
        browser.displayActionButton = NO;
        browser.displayLikeButton = NO;
        browser.displayCommentButton = NO;
        browser.displayEnterTripButton = NO;
        browser.displayDeleteButton = NO;
        browser.displaySelectionDoneButton = YES;
        browser.displaySelectionButton = YES;
        
        // Modal
        TopViewAutorotateNavViewController *nc = [[TopViewAutorotateNavViewController alloc] initWithRootViewController:browser];
        nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self.albumVC presentModalViewController:nc animated:YES];*/
    } else {
        EditVideoViewController *editVideo = [[EditVideoViewController alloc] initWithAsset:imgAsset];
        editVideo.delegate = self.albumVC;
        editVideo.hidesBottomBarWhenPushed = YES;
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:editVideo];
        [self.albumVC presentViewController:nav animated:YES completion:nil];
    }
}


#warning 去掉MWPhotoBrowser 相关部分
/*
#pragma mark -
#pragma mark MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return self.photoBrowserArr.count;
}

- (id<MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    MWPhoto *photo = nil;
    if (index < self.photoBrowserArr.count) {
        ImageAsset *imgAsset = [self.photoBrowserArr objectAtIndex:index];
        
        ALAsset *asset = imgAsset.asset;
        
        UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
        photo = [MWPhoto photoWithImage:image];
        photo.isSelected = [self.selectedAssets containsObject:imgAsset];
    }
    return photo;
}

- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index
{
    return nil;
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser toggleSelectionOfPhotoAtIndex:(NSInteger)index
{
    if (index < self.photoBrowserArr.count) {
        ImageAsset *imgAsset = [self.photoBrowserArr objectAtIndex:index];
        
        if (![self.selectedAssets containsObject:imgAsset] && imgAsset.asset) {
            if (self.selectedAssets.count >= self.imageCntLimitation) {
                [QWImageMangerConfig alert:[NSString stringWithFormat:QWImagePickerLocalizedString(@"A maximum of %d images can be selected.", nil), self.imageCntLimitation]];
                return NO;
            }
            
            [self.selectedAssets addObject:imgAsset];
        } else if (imgAsset.asset) {
            [self.selectedAssets removeObject:imgAsset];
        }
        
        return YES;
    }
    
    return NO;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser backWithMWPhoto:(MWPhoto *)currentPhoto atIndex:(NSInteger)index
{
    [self reloadTableViewAndData:NO];
    [self.albumVC updateNavBarTitleView];
}

- (NSInteger)numberOfSelectedPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return [self.selectedAssets count];
}

- (void)completeSelectionOfPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    [self.albumVC doneBtnPressed:nil];
}
*/
#pragma mark -
#pragma mark take a picture from camera

- (void)takeAPicture:(NSURL *)assetURL
{
    if (self.selectedAssets.count + self.takenPicURLs.count < self.imageCntLimitation) {
        [self.takenPicURLs addObject:assetURL.absoluteString];
    }
    
    // 新拍的照片只有相机胶卷（照片流不一定有），在路上能看到
    ALAssetsGroup *group = self.selectedGroup.assetGroup;
    if ([[group valueForProperty:ALAssetsGroupPropertyType] intValue] == ALAssetsGroupSavedPhotos ||
        [[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:APP_ALBUM_NAME]){
        return;
    }
    
    MyAssetsGroup *myGroup = [self.assetGroups firstObject];
    
    self.selectedGroup = myGroup;
    
    [self.albumVC.albumTableView reloadData];
    [self.albumVC hideAlbumTableView];
    [self.albumVC updateNavBarTitleView];
    
    [self reloadTableViewAndData:YES];
}

@end
